<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\BannerCategory;
use app\admin\model\Banner;
use think\facade\Log;

class BannerCategoryService
{
    /**
     * 列表
     * @return void
     */
    public function getBannerCategoryList($pageSize = 10)
    {
        $model = new BannerCategory();
        return $model->order('id desc')->paginate($pageSize);
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        if (empty($data)) {
            return false;
        }
        $model = new BannerCategory();
        try {
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit BannerCategory error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        $model = new BannerCategory();
        // 判断该分类下是否含有记录
        $item = (new Banner())->where(['category_id'=>$id, 'delete_time'=>0])->find();
        if ($item) {
            return ['code'=>1, 'msg'=>'删除失败，该分类下含有记录'];
        }
        if ($model::destroy($id)) {
            return ['code'=>0, 'msg'=>'删除成功'];
        } else {
            return ['code'=>1, 'msg'=>'删除失败'];
        }
    }

    /**
     * 查询一条记录
     * @param $id
     * @return void
     */
    public function getOne($id)
    {
        $model = new BannerCategory();
        return $model->find($id);
    }

    /**
     * 获取分类名称
     * @param $categoryId
     * @return void
     */
    public function getName($categoryId)
    {
        $model = new BannerCategory();
        return $model->where('id', $categoryId)->value('name');
    }
}